from baseview import BaseView
from ..bases import widgets
from .. import editors
from ..childgroup_list import ChildGroupList

class DefinitionsView(BaseView):
    topwidget_name = 'Device Definitions'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(DefinitionsView, self).__init__(**kwargs)
        self.DeviceSystem = self.MainController.DeviceSystem
        self.device_editor = None
        
        vbox = widgets.VBox()
        col_attrs = ['id', 'manufacturer', 'name', 'personality_mode']
        col_names = [s.replace('_', ' ').title() for s in col_attrs]
        list_types = [str] * 4
        dlkwargs = dict(name='Definitions', 
                        child_group=self.DeviceSystem.DefinedDevices, 
                        col_attrs=col_attrs, 
                        col_names=col_names, 
                        list_types=list_types)
        self.device_list = self.add_editor(ChildGroupList, **dlkwargs)
        self.device_list.bind(current_child=self.on_device_list_current_child_set)
        vbox.pack_start(self.device_list.topwidget, expand=True)
        
        hbox = widgets.HBox()
        d = {'btnNewDevice':'New Device', 'btnDelDevice':'Delete'}
        for k, v in d.iteritems():
            btn = self.make_child_widget(widgets.Button, k, label=v)
            btn.connect('clicked', self.on_device_list_btns_clicked, k)
            hbox.pack_start(btn)
        vbox.pack_start(hbox)
        
        self.topcontainer.pack_start(vbox)
        self.topwidget.show_all()
        
    def on_device_list_current_child_set(self, **kwargs):
        device = kwargs.get('value')
        self.set_current_device(device)
        
    def set_current_device(self, obj):
        self.remove_editor('device_editor')
        if obj is None:
            return
        self.add_editor(editors.DeviceEditor, 'device_editor', device=obj)
        self.topcontainer.pack_start(self.device_editor.topwidget)
        
    def on_device_list_btns_clicked(self, btn, key):
        if key == 'btnNewDevice':
            device = self.DeviceSystem.add_definition(name='New Device')
            self.device_list.current_child = device
        elif key == 'btnDelDevice':
            device = self.device_list.current_child
            if device is not None:
                self.DeviceSystem.del_definition(device=device)

UI_VIEW = DefinitionsView
